package com.example.hello.client.CellTable;

import com.example.hello.BootstrapCellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.view.client.CellPreviewEvent;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentConnector;
import com.vaadin.shared.ui.Connect;

import java.util.HashMap;
import java.util.List;

@Connect(BootstrapCellTable.class)
public class BootstrapCellTableConnector extends AbstractComponentConnector implements CellPreviewEvent.Handler {

    private BootstrapCellTableRpc rpc = RpcProxy.create(BootstrapCellTableRpc.class, this);

    public BootstrapCellTableConnector() {
        getWidget().addCellPreviewHandler(this);
    }

    @Override
    public BootstrapCellTableState getState() {
        return (BootstrapCellTableState) super.getState();
    }

    @Override
    public VBootstrapCellTable getWidget() {
        return (VBootstrapCellTable) super.getWidget();
    }

    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        final VBootstrapCellTable cellTable = getWidget();
        BootstrapCellTableState state = getState();

        List<String> columnPropertyNames = state.getColumnPropertyNames();

        //establish columns
        for (String pn : columnPropertyNames) {
            final String propertyName = pn;
            TextColumn<HashMap<String, String>> column = new TextColumn<HashMap<String, String>>() {
                @Override
                /*
                    tableEntry: the HashMap representing property name (key)
                                and property values of a row entry
                 */
                public String getValue(HashMap tableEntry) {
                    return (String) tableEntry.get(propertyName);
                }
            };
            cellTable.addColumn(column, propertyName);
        }
        //add rows
        cellTable.setRowData(0, state.getRows());

        cellTable.setBordered(state.isBordered());
        cellTable.setCondensed(state.isCondensed());
        cellTable.setStriped(state.isStriped());
        cellTable.setHover(state.isHovered());
    }

    @Override
    public void onCellPreview(CellPreviewEvent event) {
//        MouseEventDetails details = MouseEventDetailsBuilder.buildMouseEventDetails(
//                event.getNativeEvent(), getWidget().getElement());
//        if (BrowserEvents.CLICK.equals(event.getNativeEvent().getType())) {
//            @SuppressWarnings("unchecked")
//            String name = ((HashMap<String, String>) event.getValue()).get("name");
//            rpc.click(details, name);
//        }
    }

}
